//
//  SwiftTimer.swift
//  PPKit
//
//  Created by xiaopin on 20/9/27.
//  Copyright © 2020年 pinguo. All rights reserved.
//  https://gitee.com/xiaopindev/PPKit
//  https://github.com/xiaopindev
//  https://xiaopin.cnblogs.com

/*
 //开启定时器
 SwiftTimer.shared.scheduledGCDTimer(key: "mytimer1", timeInterval: 1, queue: .main, repeats: true) {
      //需要执行的代码
  }
 
 //取消定时器
 SwiftTimer.shared.cancelTimer(key: "mytimer1")
 
 //检查是否存在
 SwiftTimer.shared.isExistTimer(key: "mytimer1")
 **/

public class SwiftTimer {
    //单例
    static let shared = SwiftTimer()
    
    lazy var timerPool = [String: DispatchSourceTimer]()
    
    /// GCD定时器
    ///
    /// - Parameters:
    ///   - name: 定时器名字
    ///   - timeInterval: 时间间隔
    ///   - queue: 队列
    ///   - repeats: 是否重复
    ///   - action: 执行任务的闭包
    func scheduledGCDTimer(key name: String?, timeInterval: Double, queue: DispatchQueue, repeats: Bool, action: @escaping (()->())) {
        if name == nil {
            return
        }
        
        var timer = timerPool[name!]
        if timer == nil {
            timer = DispatchSource.makeTimerSource(flags: [], queue: queue)
            timer?.resume()
            timerPool[name!] = timer
        }
        //精度0.1秒
        timer?.schedule(deadline: .now(), repeating: timeInterval, leeway: DispatchTimeInterval.milliseconds(100))
        timer?.setEventHandler(handler: { [weak self] in
            action()
            if repeats == false {
                self?.cancelTimer(key: name)
            }
        })
    }
    
    /// 取消定时器
    /// - Parameter name: 定时器名字
    func cancelTimer(key name: String?) {
        let timer = timerPool[name!]
        if timer == nil { return }
        timerPool.removeValue(forKey: name!)
        timer?.cancel()
    }
    
    /// 检查定时器是否已存在
    ///
    /// - Parameter name: 定时器名字
    /// - Returns: 是否已经存在定时器
    func isExistTimer(key name: String?) -> Bool {
        if timerPool[name!] != nil {
            return true
        }
        return false
    }
}
